package br.biofoco.p2p.rpc;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

public class CustomEndPointDeserializer extends JsonDeserializer<EndPoint> {

	@Override
	public EndPoint deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {

		EndPoint endpoint = null;
		Map<String,String> map = new HashMap<String,String>();
		while ( jp.nextToken() != JsonToken.END_OBJECT ) {
			if ( jp.getCurrentToken() == JsonToken.FIELD_NAME ) {				
				String fieldName = jp.getCurrentName();				
				jp.nextToken();				
				map.put(fieldName, jp.getText());
			}
		}		
		endpoint = createEndpoint(map);		
		return endpoint;
	}

	private EndPoint createEndpoint(Map<String, String> map) {
		
		String address = map.get("address");
		Protocol protocol = Protocol.of(map.get("protocol"));
		int port = Integer.parseInt(map.get("port"));		
		
		EndPoint ep = new EndpointFactory().createEndpoint(protocol, address, port);
		return ep;
	}
		

}
